<script setup lang="ts">
import * as tf from '@tensorflow/tfjs';
import * as knn from '@tensorflow/tfjs-converter';
import { onMounted } from 'vue';
 
// 模型 URL，可以是本地或远程地址
const MODEL_URL = 'https://storage.googleapis.com/tfjs-models/savedmodel/mnist_model_webgl';
 
console.log('kkkk', knn)

// 加载预训练的 MNIST KNN 模型
const model = knn.loadGraphModel(MODEL_URL);
 
onMounted(() => {
  // 准备好画布和相关元素
  const canvas = document.getElementById('canvas');
  const context = canvas.getContext('2d');
  
  // 用户界面的函数
  function clearCanvas() {
    context.fillStyle = 'white';
    context.fillRect(0, 0, canvas.width, canvas.height);
  }
  
  function classify() {
    debugger
    // 获取画布数据并转换为张量
    const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
    const data = tf.tensor(imageData.data, [1, 28, 28, 1]);
  
    // 对数据进行预处理并分类
    model.classify(data, 5).then(predictions => {
      // 处理预测结果
      console.log('Predictions:', predictions);
      for (let i = 0; i < predictions.length; i++) {
        console.log(`${predictions[i].className}: ${predictions[i].probability}`);
      }
    });
  
    data.dispose();
  }
  
  // 监听鼠标事件并在画布上绘制
  canvas.addEventListener('mousedown', (e) => {
    const x = e.offsetX;
    const y = e.offsetY;
    context.beginPath();
    context.arc(x, y, 10, 0, 2 * Math.PI);
    context.fill();
  });
  
  // 用户界面的按钮绑定分类函数
  document.getElementById('classify-btn').addEventListener('click', classify);
  
  // 清除画布
  // clearCanvas();
})
</script>

<template>
  <div>
   <canvas style="height: 200px; width: 640px;" id="canvas"></canvas>
   <button id="classify-btn">Run</button>
  </div>
</template>
